//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by gaoliang on 15/11/8.
//  Copyright © 2015年 gaoliang. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        
        // 设置主题色
        setThemeColor()
        // 注册通知
        refisterNotification()


//        //   设置根视图控制器
//        let nav = UINavigationController(rootViewController: composeViewController())
        
        window?.rootViewController =   defaulterController()

        return true
    }
    
    // 监听通知
    private func refisterNotification() {
                NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name:AppSwitchRootViewControler, object: nil)
    }
    @objc private func switchToRootVC (n: NSNotification) {
        if (n.object as? String) != nil {
            window?.rootViewController = WelViewController()
        }
        
        window?.rootViewController = MainViewController()
    }
    
    // 根据不同用户显示不同界面
    private func defaulterController() -> UIViewController{
        if UserAccountViewModel().userLogin{
        
//            // 判断是否是新版本
//            if isNewVersion() {
//            
//                return NewFectureViewController()
//            }
//            return  WelViewController()
            return isNewVersion() ? NewFectureViewController() : WelViewController()
        }
        return MainViewController()
    }
    
    private func isNewVersion() -> Bool {
        
    
        // 1.获取新版本
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionStr)
        // 2.获取旧版本
        let key = "sandBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        // 3.保存新版本
        userdefaults.setDouble(versionNum!, forKey: key)
            // 同步沙盒
        userdefaults.synchronize()
        // 4.比较新旧版本
        return versionNum! > lastVersion
    }

    private func setThemeColor() {
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }

}

